/*!
 * 数据表格v1.0
 *
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 */
(function( $, undefined ) {
	$.widget( "grass.pagination", {
		version: "1.0",
		defaultElement: "<div>",
		regional: {
			first: "首页",
			prev: "上一页",
			next: "下一页",
			last: "尾页"
		},
		options: {
			total: 1,// 记录总数，应该在创建pagination时设置。
			pageCount: null,
			pageSize: 10,// 页面尺寸。（译者注：每页显示的最大记录数）
			pageNumber: 1,// 创建pagination时显示的页码。
			onPageClick: function(){}// 点击分页时触发
		},
		
		_create: function() {
			this.container = $("<ul></ul>").addClass("pagination").appendTo(this.element);
			
			this.container.append(this._createListItems(this.getPages(this.options.pageNumber)));
			
			this.goToPage(this.options.pageNumber);
			
			if($.isNumeric(this.options.pageCount)){
				this.totalPage = this.options.pageCount;
			}else{
				this.totalPage = this.options.total % this.options.pageSize == 0?
	            		this.options.total/this.options.pageSize : 
	            			parseInt(this.options.total/this.options.pageSize) + 1;
			}
			
		},
		setPageCount: function(pageCount){
			this.options.pageCount = pageCount;
			this.totalPage = pageCount;
		},
		setTotal: function(total){
			this.options.total = total;
			this.totalPage = this.options.total % this.options.pageSize == 0?
            		this.options.total/this.options.pageSize : 
            			parseInt(this.options.total/this.options.pageSize) + 1;
		},
		goToPage: function(pageNumber){
			 if (pageNumber < 1 || pageNumber > this.totalPage) {
               $.error('Page is incorrect.');
			 }
			 this.render(pageNumber, this.getPages(pageNumber));
			 this._setupEvents();
		},
		
		_setupEvents: function(){
			var self = this;
           this.container.find('li').each(function () {
               var $this = $(this);
               $this.off();
               if ($this.hasClass('disabled') || $this.hasClass('active')) return;
               $this.click(function () {
            	   self.options.onPageClick(parseInt($this.data('page'), 10), 
                		   self.options.pageSize);
                   self.goToPage(parseInt($this.data('page'), 10));
               });
               
           });
		},
		
		_createListItems: function(pages){
			 var listItems = $();

            listItems = listItems.add(this._createItem('first', 1));
            listItems = listItems.add(this._createItem('prev', 1));

            for (var i = 0; i < pages.length; i++) {
                listItems = listItems.add(this._createItem('page', pages[i]));
            }

            listItems = listItems.add(this._createItem('next', 2));
            listItems = listItems.add(this._createItem('last', this.totalPage));

            return listItems;
		},
		
		_createItem: function(type, page){
			var itemContainer = $('<li></li>'),
            itemContent = $('<a></a>'),
            itemText = null;

	        itemContainer.addClass(type);
	        itemContainer.attr('data-page', page);
	
	        switch (type) {
	            case 'page':
	                itemText = page;
	                break;
	            case 'first':
	                itemText = $.grass.pagination.prototype.regional.first;
	                break;
	            case 'prev':
	                itemText = $.grass.pagination.prototype.regional.prev;
	                break;
	            case 'next':
	                itemText = $.grass.pagination.prototype.regional.next;
	                break;
	            case 'last':
	                itemText = $.grass.pagination.prototype.regional.last;
	                break;
	            default:
	                break;
	        }
	
	        return itemContainer.append(itemContent.text(itemText));
		},
		
		getPages: function (pageNumber) {
            var pages = [];

            var half = Math.floor(this.options.pageSize / 2);
            var start = pageNumber - half + 1 - this.options.pageSize % 2;
            var end = pageNumber + half;
            
            // handle boundary case
            if (start <= 0) {
                start = 1;
                end = this.options.pageSize;
            }
            if (end > this.totalPage) {
                end = this.totalPage;
            }

            var itPage = start;
            while (itPage <= end) {
                pages.push(itPage);
                itPage++;
            }

            return pages;
        },
        
        render: function(pageNumber, pages){
            this.container.empty();
            this.container.append(this._createListItems(pages));

            this.container.find('.page').removeClass('active');
            this.container.find('.page').filter('[data-page="' + pageNumber + '"]').addClass('active');

            this.container.find('.first')
                .toggleClass('disabled', pageNumber === 1);

            this.container.find('.last')
                .toggleClass('disabled', pageNumber === this.totalPage);

            var prev = pageNumber - 1;
            this.container.find('.prev')
                .toggleClass('disabled', pageNumber === 1)
                .data('page', prev > 1 ? prev : 1);

            var next = pageNumber + 1;
            this.container.find('.next')
                .toggleClass('disabled', pageNumber === this.totalPage)
                .data('page', next < this.totalPage ? next : this.totalPage);
        },
        
		destroy: function() {
			this.container.remove();
		}
	});
	

}(jQuery));
